#include "ImportDataDialog.h"

ImportDataDialog::ImportDataDialog(QDialog *parent)
    : QDialog(parent),
    mNeedInit(true)
{
	ui.setupUi(this);

	ui.importFileNameEdit->setEnabled(false);
	ui.importFileNameEdit->setReadOnly(true);
	ui.importColumnNameWidget->setHeaderHidden(true);

	QObject::connect(ui.closeButton, SIGNAL(clicked()), this, SLOT(accept()));
	QObject::connect(ui.openImportFileButton, SIGNAL(clicked()), this, SLOT(selectImportFile()));
	QObject::connect(ui.importColumnNameWidget, SIGNAL(itemClicked(QTreeWidgetItem*, int)),
			this, SLOT(itemClicked(QTreeWidgetItem*, int)));
	QObject::connect(ui.importButton, SIGNAL(clicked()), this, SLOT(import()));
}

ImportDataDialog::~ImportDataDialog()
{

}

void ImportDataDialog::showThisDialog()
{
	/*if (mNeedInit)
	{
		setImportColumnList();
		mNeedInit = false;
	}*/
	this->exec();
}

void ImportDataDialog::selectImportFile()
{
	mImportFileName = QFileDialog::getOpenFileName(this,
	     tr("Open Import File"), "./backup", tr("Import Files (*.txt)"));
	//cout<<"ImportDataDialog::selectImportFile-->mImportFileName="<<mImportFileName.toUtf8().data()<<endl;
	if (!mImportFileName.isEmpty())
	{
		ui.importFileNameEdit->setEnabled(true);
		ui.importFileNameEdit->setText(mImportFileName);
		setImportColumnList();
	}
	else
	{
		ui.importFileNameEdit->setEnabled(false);
		ui.importFileNameEdit->clear();
	}
}

void ImportDataDialog::setImportColumnList()
{
	ui.importColumnNameWidget->clear();
	QFile file(mImportFileName);
	 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
		 return;

	 QTextStream in(&file);
	 QString curTable;
	 //QStringList colNames;
	 //QVector<QStringList> valVec;
	 bool isColName=false;
	 while (!in.atEnd())
	 {
		 QString line = in.readLine();
		 if (line.contains("[Table]"))
		 {
			 curTable = line;
			 curTable.remove("[Table]");
			 curTable = curTable.simplified();
			 isColName=true;
			 //updateDB(colNames, valVec);
		 }
		 else if (!curTable.isEmpty())
		 {
			if (isColName)
			{
				isColName = false;
				mColNames[curTable] = line.split("<sep>", QString::SkipEmptyParts);
			}
			else
			{
				QStringList vals = line.split("<sep>", QString::SkipEmptyParts);
				if (mColNames[curTable].size() != vals.size())
				{
					cout	<<"ImportDataDialog::setImportColumnList-->mColNames[curTable]="
							<<mColNames[curTable].join(",").toUtf8().data()
							<<"\tsize="<<mColNames[curTable].size()<<endl;
					cout	<<"ImportDataDialog::setImportColumnList-->vals="
							<<vals.join(",").toUtf8().data()
							<<"\tsize="<<vals.size()<<endl;
				}
				assert(mColNames[curTable].size() == vals.size());
				mValVec[curTable].push_back(vals);
			}
		 }
		 else
		 {
			 cout<<"ImportDataDialog::setImportColumnList-->Invalid line."<<endl;
			 assert(0);
		 }
	 }

	//QString command;
	//command = QString("SELECT name FROM sqlite_master WHERE type='table'");
	//DB.quickGet(command);
	for (	map<QString, QStringList>::iterator table_it = mColNames.begin();
			table_it != mColNames.end();
			table_it++)
	{
		QString tableName = table_it->first;
		QStringList colName =  table_it->second;
		QTreeWidgetItem* tableItem =
			new QTreeWidgetItem(ui.importColumnNameWidget, QStringList(tableName));
		tableItem->setCheckState(0, Qt::Checked);
		mTableNames.push_back(tableName);
		for (int i=0; i<colName.size(); i++)
		{
			//QTreeWidgetItem* tableItem = tableItems[0];
			QTreeWidgetItem* colItem = new QTreeWidgetItem(tableItem, QStringList(colName[i]));
			colItem->setCheckState(0, Qt::Checked);
		}
	}

	ui.importColumnNameWidget->setIndentation(10);
	ui.importColumnNameWidget->expandAll();
}

void ImportDataDialog::itemClicked(QTreeWidgetItem* item, int column)
{
	//cout<<"ExportDataDialog::itemPressed-->item "<<item->text(column).toUtf8().data()<<endl;
	if (item->checkState(column) == Qt::Unchecked)
	{
		//cout<<"ExportDataDialog::itemPressed--> Qt::Unchecked"<<endl;
		item->setCheckState(column, Qt::Checked);
		for (int i=0; i<item->childCount(); i++)
			item->child(i)->setCheckState(column, Qt::Checked);
	}
	else if (item->checkState(column) == Qt::Checked)
	{
		//cout<<"ExportDataDialog::itemPressed--> Qt::Checked"<<endl;
		item->setCheckState(column, Qt::Unchecked);
		for (int i=0; i<item->childCount(); i++)
			item->child(i)->setCheckState(column, Qt::Unchecked);
	}
	else if (item->checkState(column) == Qt::PartiallyChecked)
	{
		//cout<<"ExportDataDialog::itemPressed--> Qt::Checked"<<endl;
		item->setCheckState(column, Qt::Checked);
		for (int i=0; i<item->childCount(); i++)
			item->child(i)->setCheckState(column, Qt::Checked);
	}
	else
	{
		cout<<"ExportDataDialog::itemClicked-->unexpected check state"<<endl;
		assert(0);
	}

	if (item->parent())
	{
		//cout<<"ExportDataDialog::itemPressed-->lowser level"<<endl;
		bool allChecked=true;
		bool allUncheked=true;
		for (int i=0; i<item->parent()->childCount(); i++)
		{
			if (item->parent()->child(i)->checkState(column) != Qt::Checked)
				allChecked = false;
			if (item->parent()->child(i)->checkState(column) != Qt::Unchecked)
				allUncheked = false;
		}
		if (allChecked)
			item->parent()->setCheckState(column, Qt::Checked);
		else if(allUncheked)
			item->parent()->setCheckState(column, Qt::Unchecked);
		else
			item->parent()->setCheckState(column, Qt::PartiallyChecked);
	}
}

void ImportDataDialog::import()
{
	QString command;
	for (int i=0; i<ui.importColumnNameWidget->topLevelItemCount(); i++)
	{
		if (	ui.importColumnNameWidget->topLevelItem(i)->checkState(0) == Qt::Checked
			||	ui.importColumnNameWidget->topLevelItem(i)->checkState(0) == Qt::PartiallyChecked)
		{
			QString tableName = ui.importColumnNameWidget->topLevelItem(i)->text(0);
			QStringList& colNameList = mColNames[tableName];
			QVector<QStringList>& valListVec = mValVec[tableName];
			//int blockSize=500;
			DB.quickUpdate("BEGIN");
			for (int j=0; j<valListVec.size(); j++)
			{
				int index_id = colNameList.indexOf("id");
				int id = valListVec[j][index_id].toInt();
				command = QString("update %1 set ").arg(tableName);
				for (int k=0; k<colNameList.size(); k++)
				{
					if (colNameList[k] != QString("id") && valListVec[j][k] != QString("<NULL>"))
						command.append(QString(" %1='%2', ").arg(colNameList[k], valListVec[j][k]));
				}
				command.remove(command.lastIndexOf(","), 1);
				command.append(QString(" where id=%1;").arg(id));
				DB.quickUpdate(command);
			}
			DB.quickUpdate("COMMIT");
		}
	}

	this->accept();
}
